package org.example.server.controller;

import org.example.common.properties.EmailProperties;
import org.example.common.result.Result;
import org.example.common.utils.EmailOperatorRecognizer;
import org.example.common.utils.emailUtil;
import org.example.common.utils.VerificationCodeUtil;
import org.example.pojo.user.userGetCodeDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.mail.Session;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
public class getCode {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private Map<String, Session> sessionMap;
    @Autowired
    private EmailProperties emailProperties;
    @RequestMapping(value="/register/getCode",method = RequestMethod.POST)
    public Result getCode(@RequestBody userGetCodeDto  xxx) {
        String code = VerificationCodeUtil.generateVerificationCode();
//        String username = dto.getUsername() ;
//        String qq = dto.getYouxiang();
        String s = EmailOperatorRecognizer.recognizeOperator(xxx.getYouxiang());
        System.out.println(s);
        // 验证码缓存到redis中，key为手机号，value为验证码
        redisTemplate.opsForValue().set(xxx.getYouxiang() ,code,60, TimeUnit.SECONDS);
        //发送验证码
        Session session = sessionMap.get(s);
        String myCode = emailProperties.getSenders().get(s).getUsername();
        System.out.println(myCode);
        emailUtil.sent(code, xxx.getYouxiang(),session,myCode);



        return Result.success("验证码发送成功");
    }
}
